package com.fitmanagement.controller;


import cn.hutool.crypto.SecureUtil;
import cn.hutool.jwt.JWTUtil;
import com.fitmanagement.entity.Result;
import com.fitmanagement.entity.Users;
import com.fitmanagement.exception.ServiceException;
import com.fitmanagement.service.*;
import com.fitmanagement.utils.TokenUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;

import java.util.HashMap;
import java.util.List;

import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 虚空
 * @since 2024-10-25
 */
@RestController
@RequestMapping("/users")
@RequiredArgsConstructor // 自动注入
public class UsersController {

    private final IUsersService usersService;


    @GetMapping("/getAll")
    public List<Map<String, Object>> index(){
        List<Map<String, Object>> maps = usersService.listMaps();
        return maps;
    }
    @DeleteMapping("/Delete/{id}")
    public Boolean Delete(@PathVariable("id") int id) {
        
        Boolean result = usersService.removeByUserId(id);
        if (result) {
            System.out.println("User with ID: " + id + " deleted successfully.");
        } else {
            System.out.println("Failed to delete user with ID: " + id);
        }
        return result;
    }

    @GetMapping("/Search")
    public List<Map<String, Object>> Search(@RequestParam("username") String username){
        return usersService.SearchByName(username);
    }
    @PostMapping("/add")
    public Boolean add(@RequestBody Users user) {

        user.setCreatedAt(LocalDateTime.now());
        user.setUpdatedAt(LocalDateTime.now());
        return usersService.save(user);
    }

    @PutMapping("/updateId/{id}")
    public Result updateUser(@PathVariable int id, @RequestBody @Validated Users user) {
        usersService.updateUser(id, user.getUsername(), user.getPassword(), user.getEmail(), user.getDateOfBirth().atStartOfDay(), user.getGender());
        return Result.success();
    }
    @GetMapping("/{id}")
    public Result getUserById(@PathVariable("id") int id) {
        Users user = usersService.getById(id);
        return Result.success(user);
    }
    @PostMapping("/login")
    public Result<Users> login(@RequestParam String email, @RequestParam String password) {
        Users loginUser = usersService.findByEmail(email);

        if (loginUser == null) {
            return Result.error("邮箱不存在", "s");
        }
        if (!password.equals(loginUser.getPassword())){
            throw new ServiceException("用户名或密码错误");
        }
        String token = TokenUtils.createToken(loginUser.getUserID().toString(), loginUser.getPassword());
        loginUser.setToken(token);
        System.out.println(token);

        return Result.success(loginUser);

//        String md5String = SecureUtil.md5(loginUser.getPassword());


}

        // 校验密码
//        if (SecureUtil.md5(password).equals(md5String)) {
            //         登录成功，生成 Token
//            Map<String, Object> claims = new HashMap<>();
//            claims.put("id", loginUser.getUserID());
//            claims.put("email", loginUser.getEmail());
//            Map<String, Object> claims = new HashMap<String, Object>() {
//                private static final long serialVersionUID = 1L;
//                {
//                    put("email", loginUser.getEmail());
//                    put("expire_time", System.currentTimeMillis() + 1000 * 60 * 60 * 24 * 15);
//                }
//            };
//            String token = JWTUtil.createToken(claims, loginUser.getPassword().getBytes());
//            System.out.println(token);
//
//            return Result.success(token);
//        }return Result.error("登录失败","sad"); // 返回 token
//    }
//

}
